<template>
    <div>
        <basic-container>
            <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
                <el-form-item label="敏感词" class="margin-style">
                    <el-input v-model.trim="searchForm.keyWords" maxlength="20" placeholder="请输入敏感词"></el-input>
                </el-form-item>
                <div>
                    <el-form-item label="匹配词:" class="margin-style">
                        <el-input v-model.trim="searchForm.matching" placeholder="请输入匹配词"></el-input>
                    </el-form-item>

                    <el-form-item label="所属分组:" class="margin-style" prop="groupId">
                        <el-select v-model="searchForm.groupId" placeholder="请选择" @focus="getGroupList()">
                            <el-option v-for="item in searchGroupList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="search('searchForm')">搜索</el-button>
                    <el-button @click="clearInput('searchForm')">清空</el-button>
                </el-form-item>
            </el-form>

            <div>
                <el-button type="primary" @click="addWords">新建敏感词</el-button>
                <el-button type="primary" @click="addGroup">新建分组</el-button>
                <el-button type="primary" @click="editGroup">修改分组</el-button>
            </div>
            <!-- 以下是表格内容 -->
            <div class="madp-table">
                <el-table
                    :header-cell-style="{
                        background: 'rgb(255, 191, 191)',
                        color: 'rgb(44,44,44)'
                    }"
                    :data="tableData"
                    stripe
                    v-loading="loading"
                >
                    <el-table-column fixed prop="sensitiveWordId" align="center" label="序号" width="60">
                        <template slot-scope="scope">
                            <span v-text="getIndex(scope.$index)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" align="center" label="敏感词" width="120">
                        <template slot-scope="scope">
                            <div>{{ scope.row.name || '—' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="matchingWords" align="center" label="匹配词">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" width="200" trigger="hover" v-if="scope.row.matchingRule && scope.row.matchingRule.length > 0">
                                <div>
                                    <el-tag type="primary" style="margin: 2px" v-for="(item, index) in scope.row.matchingRule" :key="index">{{ item }}</el-tag>
                                </div>
                                <div slot="reference">
                                    <el-tag type="primary" style="margin: 2px" v-for="(item, index) in scope.row.matchingRule ? scope.row.matchingRule.slice(0, 2) : []" :key="index">{{
                                        item
                                    }}</el-tag>
                                    <el-tag type="primary" style="margin: 2px" v-if="scope.row.matchingRule && scope.row.matchingRule.length > 2">...</el-tag>
                                </div>
                            </el-popover>
                            <div v-else>—</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="employeeNum" align="center" label="员工触发次数" width="180">
                        <template slot-scope="scope">
                            <div>
                                {{ scope.row.employeeNum === 0 ? 0 : scope.row.employeeNum || '—' }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="contactNum" align="center" label="客户触发次数" width="180">
                        <template slot-scope="scope">
                            <div>
                                {{ scope.row.contactNum === 0 ? 0 : scope.row.contactNum || '—' }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="groupName" align="center" label="所属分组" width="120">
                        <template slot-scope="scope">
                            <div>{{ scope.row.groupName || '—' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="messageReminder" align="center" label="消息提醒" width="120">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.messageAlertStatus" :active-value="1" :inactive-value="2" @change="(e) => statusChange(e, scope.row, 'messageAlertStatus')"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" align="center" label="是否开启" width="120">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="(e) => statusChange(e, scope.row, 'status')"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" align="center" label="创建时间" width="220">
                        <template slot-scope="scope">
                            <div>{{ scope.row.createTime || '—' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center" width="140">
                        <template slot-scope="scope">
                            <el-button @click="handleEdit(scope.row, tableData)" type="text">编辑</el-button>
                            <el-button @click="handleClick(scope.row, tableData)" type="text">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="madp-pagination-wrap">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page.currentPage"
                    :page-sizes="[10, 20, 30, 50, 100]"
                    :page-size="page.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total"
                ></el-pagination>
            </div>
            <!-- 以下是新建敏感词弹框 -->
            <div>
                <el-dialog :close-on-click-modal="false" :title="`${dialogType}敏感词`" v-if="dialogVisible" :visible.sync="dialogVisible" width="900px" :before-close="handleClose">
                    <el-form :rules="add" ref="refForm" :model="refForm">
                        <el-form-item label="所属分组:" prop="groupId" label-width="18%">
                            <el-select v-model="refForm.groupId" placeholder="请选择" class="madp-add" @change="changeGroupId">
                                <el-option v-for="item in groupList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="敏感词名称:" prop="name" label-width="18%">
                            <el-input v-model.trim="refForm.name" class="madp-add" placeholder="请输入敏感词名称" maxlength="20" @input="refForm.name = refForm.name.replace(/\s+/, '')"></el-input>
                        </el-form-item>
                        <el-form-item label="匹配规则:" prop="matchingRule" label-width="18%">
                            <el-input
                                class="madp-add"
                                placeholder="请输入匹配词，多个匹配词用‘，’（中文逗号）隔开"
                                v-model="refForm.matchingRule"
                                @input="updateInput"
                                @keyup.enter.native="handleInputConfirm"
                            ></el-input>
                            <!-- <div v-if="refForm.tags[0]"> -->
                            <div v-if="tags && tags.length > 0">
                                <el-tag v-for="(tag, index) in tags" :key="index" closable :disable-transitions="false" @close="handleTagClose(tag)">
                                    {{ tag }}
                                </el-tag>
                            </div>
                        </el-form-item>
                        <el-form-item label="消息提醒:" prop="messageAlertStatus" label-width="18%">
                            <el-radio v-model="refForm.messageAlertStatus" :label="1">是</el-radio>
                            <el-radio v-model="refForm.messageAlertStatus" :label="2">否</el-radio>
                        </el-form-item>
                        <el-form-item label="是否开启:" prop="status" label-width="18%" v-if="dialogType === '修改'">
                            <el-radio v-model="refForm.status" :label="1">是</el-radio>
                            <el-radio v-model="refForm.status" :label="2">否</el-radio>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="handleClose">取消</el-button>
                        <el-button type="primary" @click="sure">确定</el-button>
                    </span>
                </el-dialog>
            </div>
            <!-- 以下是新建分组弹框 -->
            <div>
                <el-dialog
                    title="新建分组"
                    :close-on-click-modal="false"
                    :visible.sync="dialogGroupVis"
                    width="50%"
                    :before-close="
                        () => {
                            dialogGroupVis = false;
                            tags = [];
                        }
                    "
                >
                    <el-form :rules="rules" ref="addGroupForm" :model="addGroupForm">
                        <el-form-item label="分组名称:" prop="names">
                            <el-input
                                class="madp-add"
                                placeholder="请输入分组名称，按回车完成，多个分组用‘，’（中文逗号）隔开"
                                v-model="addGroupForm.names"
                                @input="updateAddGroupForm"
                                @keyup.enter.native="handleInputAddGroupForm"
                            ></el-input>
                            <div v-if="tags && tags.length > 0">
                                <el-tag v-for="(tag, index) in tags" :key="index" closable :disable-transitions="false" @close="handleTagClose(tag)">{{ tag }}</el-tag>
                            </div>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button
                            @click="
                                dialogGroupVis = false;
                                tags = [];
                            "
                            >取消</el-button
                        >
                        <el-button type="primary" @click="groupSure">确定</el-button>
                    </span>
                </el-dialog>
            </div>
            <!-- 以下是修改分组弹框 -->
            <div>
                <el-dialog :close-on-click-modal="false" title="修改分组" :visible.sync="dialogGroupVisEd" width="50%" :before-close="handleClose2">
                    <el-form :rules="rules" ref="editGroupForm" :model="editGroupForm">
                        <el-form-item label="选择分组:" prop="groupId" label-width="18%">
                            <el-select v-model="editGroupForm.groupId" placeholder="请选择" class="madp-add">
                                <el-option v-for="item in groupList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="修改分组名称:" prop="name" label-width="18%">
                            <el-input maxlength="15" v-model.trim="editGroupForm.name" class="madp-add" placeholder="请输入分组名称"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogGroupVisEd = false">取消</el-button>
                        <el-button type="primary" @click="editGroupSure">确定</el-button>
                    </span>
                </el-dialog>
            </div>
            <!-- 以下是移动分组弹框 -->
            <div>
                <el-dialog :close-on-click-modal="false" title="移动分组" :visible.sync="dialogVisible4" width="50%" :before-close="handleClose4">
                    <div class="tag-group">
                        <el-tag v-for="item in groupList" :class="moveGroupId == item.groupId ? 'active' : ''" :key="item.groupId" @click="changeGroup(item.groupId)" style="margin-left: 15px">{{
                            item.groupName
                        }}</el-tag>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button
                            @click="
                                () => {
                                    this.dialogVisible4 = false;
                                    this.moveGroupId = '';
                                    this.moveSensitiveId = '';
                                }
                            "
                            >取消</el-button
                        >
                        <el-button type="primary" @click="moveSure">确定</el-button>
                    </span>
                </el-dialog>
            </div>
        </basic-container>
    </div>
</template>
<script>
import {
    sensitiveWordsGroupList,
    sensitiveWordsGroupAdd,
    sensitiveWordsGroupUp,
    sensitiveWordsList,
    sensitiveWordsAdd,
    sensitiveWordsEdit,
    delSensitiveWords,
    sensitiveWordsStatus,
    sensitiveWordsMove
} from '@/api/sensitive/sensitive-thesaurus.js';
export default {
    name: 'sensitiveThesaurus',
    data() {
        const matchingRuleRule = (rule, value, callback) => {
            if (this.tags && this.tags.length > 0) {
                callback();
            } else if (this.refForm.matchingRule && this.refForm.matchingRule.length > 0) {
                callback();
            } else {
                callback(new Error('请输入匹配规则'));
            }
        };
        return {
            loading: false,
            dialogVisible: false, //新建敏感词弹框
            dialogType: '',
            dialogGroupVis: false, //新建分组弹框
            dialogGroupVisEd: false, //修改分组弹框
            dialogVisible4: false, //移动分组确认弹框
            keyNameInput: '',
            //头部搜索表单
            searchForm: {
                keyWords: '',
                groupId: '' //分组id
            },
            groupList: [], //分组列表
            searchGroupList: [], //所属分组列表
            //弹出框表单
            refForm: {
                groupId: '',
                // groupName: '', //分组名称
                name: '',
                matchingRule: '',
                messageAlertStatus: 1,
                status: 1
            },
            addGroupForm: {
                names: ''
            },
            editGroupForm: {
                groupId: '',
                name: ''
            },
            isSearch: false,
            add: {
                groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
                name: [{ required: true, message: '请输入敏感词', trigger: 'blur' }],
                matchingRule: [
                    {
                        required: true,
                        validator: matchingRuleRule
                    }
                ]
            },
            rules: {
                //: [
                //     { required: true, message: "请选择", trigger: "change" }
                // ],
            },
            tableData: [],
            // 分页
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            // 分组id
            groupId: '',
            // 移动分组Id
            moveGroupId: '',
            // 移动敏感词id
            moveSensitiveId: '',
            tags: []
        };
    },
    watch: {
        tags: {
            handler() {
                if (this.$refs.refForm) {
                    this.$refs.refForm.validateField('matchingRuleRule');
                }
            },
            deep: true
        }
    },
    mounted() {
        this.getGroupList();
        this.getTableData();
    },
    methods: {
        //获取表格序号
        getIndex($index) {
            return (this.page.currentPage - 1) * this.page.pageSize + $index + 1;
        },
        //搜索
        search() {
            this.isSearch = true;
            this.page.currentPage = 1;
            this.getTableData();
        },
        //获取分组列表
        getGroupList() {
            let _this = this;
            const obj = {
                groupName: '全部',
                groupId: 0
            };
            const arr = [];
            arr.push(obj);
            sensitiveWordsGroupList().then((res) => {
                _this.groupList = res.data.data;
                res.data.data.map((item) => {
                    arr.push(item);
                });
                _this.searchGroupList = arr;
                // _this.refForm.groupName = '全部'
            });
        },
        //获取敏感词库列表
        getTableData() {
            let params = {};
            if (this.isSearch) {
                params = {
                    keyWords: this.searchForm.keyWords,
                    groupId: this.searchForm.groupId,
                    matching: this.searchForm.matching,
                    current: this.page.currentPage,
                    size: this.page.size
                };
            } else {
                params = {
                    keyWords: '',
                    groupId: 0,
                    current: this.page.currentPage,
                    size: this.page.size
                };
            }
            this.loading = true;
            sensitiveWordsList(params)
                .then((res) => {
                    this.loading = false;
                    if (res.data.code != 0) return;
                    this.tableData = res.data.data.records;
                    if (this.tableData.length == 0 && this.page.total > 0) {
                        this.page.currentPage -= 1;
                        this.getTableData();
                    }
                    this.page.total = Number(res.data.data.total);
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        handleMove() {},
        // 分页
        handleSizeChange(val) {
            this.page.size = val;
            this.getTableData(this.page);
        },
        handleCurrentChange(val) {
            this.page.currentPage = val;
            this.getTableData(this.page);
        },
        clearInput(searchForm) {
            this.keyNameInput = '';
            this.searchForm.keyWords = '';
            this.searchForm.groupId = '';
            this.searchForm.matching = '';
            if (this.$refs.searchForm) {
                this.$refs.searchForm.resetFields();
            }
            this.page.currentPage = 1;
            this.isSearch = false;
            this.getTableData();
        },
        /**
         * 新建敏感词
         */
        addWords() {
            this.dialogVisible = true;
            this.dialogType = '新建';
            this.tags = [];
            this.refForm = {
                groupId: '',
                // groupName: '', //分组名称
                name: '',
                matchingRule: '',
                messageAlertStatus: 1,
                status: 1
            };
        },
        changeGroupId() {
            this.$forceUpdate();
        },
        sure() {
            this.$refs['refForm'].validate((valid) => {
                if (valid) {
                    const matchingRule = [...new Set((this.refForm.matchingRule ? this.refForm.matchingRule.split('，') : []).concat(this.tags))];
                    if (matchingRule.length === 0) {
                        return this.$message.error('请输入敏感词');
                    }
                    const sensitiveWordDto = {
                        ...this.refForm,
                        name: this.refForm.name,
                        matchingRule: matchingRule.join(','),
                        groupId: Number(this.refForm.groupId),
                        id: this.refForm.sensitiveWordId
                    };
                    if (this.dialogType === '新建') {
                        sensitiveWordsAdd(sensitiveWordDto).then((res) => {
                            this.dialogVisible = false;
                            // this.tags = []
                            this.dialogType = '';
                            this.getTableData();
                        });
                    } else {
                        delete sensitiveWordDto.sensitiveWordId;
                        sensitiveWordsEdit(sensitiveWordDto).then((res) => {
                            this.dialogVisible = false;
                            // this.tags = []
                            this.dialogType = '';
                            this.getTableData();
                        });
                    }
                }
            });
        },
        handleClose() {
            this.dialogVisible = false;
            this.dialogType = '';
        },
        /**
         * 新建分组
         */
        addGroup() {
            this.tags = [];
            this.dialogGroupVis = true;
        },
        groupSure() {
            const names = [...new Set((this.addGroupForm.names ? this.addGroupForm.names.split('，') : []).concat(this.tags))];
            if (names.length == 0) {
                return this.$message.error('请输入分组名称');
            }
            sensitiveWordsGroupAdd({
                names: names.join(',')
            }).then((res) => {
                if (res.data && res.data.code == 0) {
                    this.$message.success('新增成功！');
                    this.dialogGroupVis = false;
                    this.addGroupForm.names = '';
                    this.getGroupList();
                    this.tags = [];
                }
            });
        },
        /**
         * 修改分组
         */
        editGroup() {
            this.dialogGroupVisEd = true;
        },
        handleClose2() {
            this.dialogGroupVisEd = false;
        },
        editGroupSure() {
            const reg = /\s+/g;
            const name = this.editGroupForm.name;
            if (!this.editGroupForm.groupId) {
                this.$message.error('请选择分组');
                return;
            }
            if (!name) {
                this.$message.error('请输入分组名称');
                return;
            }
            if (reg.test(name)) {
                this.$message.error('请输入正确的分组名称');
                return;
            }
            sensitiveWordsGroupUp(this.editGroupForm).then((res) => {
                if (res.data && res.data.code == 0) {
                    this.$message.success('修改成功！');
                    this.dialogGroupVisEd = false;
                    this.editGroupForm = {};
                    this.getGroupList();
                    this.page.currentPage = 1;
                    this.getTableData();
                }
            });
        },
        /**
         * 关闭消息提醒
         */
        statusChange(e, row, type) {
            let _this = this;
            let change = '';
            // let message = ''
            if (e == 1) {
                change = '开启';
            } else {
                change = '关闭';
            }
            let params = {
                id: row.sensitiveWordId,
                [type]: e
            };

            sensitiveWordsEdit(params).then((res) => {
                if (res.data.code === 0) {
                    _this.getTableData();
                    _this.$message({
                        type: 'success',
                        message: `${change}成功`
                    });
                }
            });
        },
        handleEdit(row) {
            this.refForm = Object.assign(this.refForm, {
                ...row,
                groupId: row.groupId.toString(),
                matchingRule: row.matchingRule.join('，')
            });
            // this.tags = JSON.parse(JSON.stringify(row.matchingRule))
            this.dialogVisible = true;
            this.dialogType = '修改';
        },
        /**
         * 删除
         */
        handleClick(row) {
            this.$confirm('删除后无法恢复，确认删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    delSensitiveWords(row.sensitiveWordId).then((res) => {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '删除成功！'
                        });
                    });
                })
                .catch(() => {});
        },
        /**
         * 移动
         */
        move(row) {
            this.dialogVisible4 = true;
            this.moveSensitiveId = row.sensitiveWordId;
            this.moveGroupId = row.groupId;
        },
        changeGroup(id) {
            this.moveGroupId = id;
        },
        handleClose4() {
            this.dialogVisible4 = false;
        },
        moveSure() {
            let params = {
                sensitiveWordId: this.moveSensitiveId,
                groupId: this.moveGroupId
            };
            sensitiveWordsMove(params).then((res) => {
                this.dialogVisible4 = false;
                this.moveGroupId = '';
                this.moveSensitiveId = '';
                this.getTableData();
                this.$message({
                    type: 'success',
                    message: '移动分组成功'
                });
            });
        },

        /**
         * 移除匹配规则标签
         */
        handleTagClose(tag) {
            this.tags.splice(this.tags.indexOf(tag), 1);
        },
        updateAddGroupForm() {
            let str = this.addGroupForm.names || '';
            str = str.replace(/\s+/g, '');
            let arr = str.split('，');
            arr = arr.map((i) => {
                if (i.length > 15) {
                    i = i.slice(0, 15);
                }
                return i;
            });
            this.addGroupForm.names = arr.join('，');
        },
        handleInputAddGroupForm() {
            if (this.addGroupForm.names) {
                let arr = this.addGroupForm.names.split('，');
                arr.map((i) => {
                    if (!this.tags.includes(i) && i) {
                        this.tags.push(i);
                    }
                });
                this.addGroupForm.names = '';
            }
        },
        updateInput() {
            let str = this.refForm.matchingRule || '';
            str = str.replace(/\s+/g, '');
            let arr = str.split('，');
            arr = arr.map((i) => {
                if (i.length > 30) {
                    i = i.slice(0, 30);
                }
                return i;
            });
            this.refForm.matchingRule = arr.join('，');
        },
        handleInputConfirm() {
            if (this.refForm.matchingRule) {
                let arr = this.refForm.matchingRule.split('，');
                arr.map((i) => {
                    if (!this.tags.includes(i) && i) {
                        this.tags.push(i);
                    }
                });
                this.refForm.matchingRule = '';
            }
        }
    }
};
</script>
<style lang="scss" scoped>
// 头部输入框
.demo-form-inline {
    display: flex;
    justify-content: flex-end;
}
.left-content-2 {
    float: left;
    .margin-style {
        margin-right: 60px;
    }
    /deep/ .el-form-item {
        margin-bottom: 0px;
    }
}
// 头部按钮
.right-content {
    float: right;
    .more {
        cursor: pointer;
        color: #409eff;
        margin-left: 20px;
    }
}

.madp-table {
    margin-top: 30px;
}
// 分页
.madp-pagination-wrap {
    float: right;
    margin-top: 20px;
    margin-bottom: 18px;
}
.madp-add {
    width: 75%;
}
.madp-toast {
    // height: 36px;
    // line-height: 36px;
    display: flex;
    align-items: center;
}
.madp-toast-img {
    width: 36px;
    height: 36px;
    margin-right: 10px;
}
.active {
    margin: 5px 10px;
    border: 2px solid #1890ff;
    border-radius: 5px;
    cursor: pointer;
}
.el-tag {
    margin: 10px 10px 0 0;
}
</style>
